package senpec.qc.harmony.base.security.jwt;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import senpec.qc.harmony.base.redis.RedisService;
import senpec.qc.harmony.system.operation.OperationService;
//import senpec.qc.harmony.system.permission.PermissionService;
import senpec.qc.harmony.system.user.User;
import senpec.qc.harmony.system.user.UserService;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;

@Component
@RequiredArgsConstructor
@Slf4j
public class JWTAuthenticationFilter extends OncePerRequestFilter {

    private final RedisService<String> redisService;

    private final JWTService jwtService;

    private final OperationService operationService;

    private final UserService userService;

//    private final PermissionService permissionService;

    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException {

        String uri = request.getRequestURI();
        String method = request.getMethod();

        log.info("doFilterInternal is running with uri : {} with method : {}", uri, method);

        String token = request.getHeader("Authorization");

        if (uri.startsWith("/auth") || uri.startsWith("/test") || uri.startsWith("/ndeReport") || uri.startsWith("/favicon") || uri.startsWith("/ai")) {
            log.info("Request uri is in white list, direct pass.");
            filterChain.doFilter(request, response);
        } else if (Objects.isNull(token)) {
            log.info("token为空。");
            filterChain.doFilter(request, response);
        } else {
            String username = jwtService.extractUsername(token);
            String tokenFromRedis = redisService.getOne(username + "-token");
            if (tokenFromRedis == null) {
                log.info("token在服务器上不存在。");
                filterChain.doFilter(request, response);
            } else if (jwtService.isTokenExpired(token)) {
                log.info("提供的token已过期。");
                filterChain.doFilter(request, response);
            } else {
                SecurityContext context = SecurityContextHolder.createEmptyContext();
//                User user = userService.getOneByCondition("username", username).getBody();
//                List<String> permissionList = permissionService.getPermissionTextListByUserId(user.getId()).getBody();
                List<String> permissionList = new ArrayList<>();
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, null, AuthorityUtils.createAuthorityList(permissionList));
                context.setAuthentication(usernamePasswordAuthenticationToken);
                SecurityContextHolder.setContext(context);
                operationService.saveEntity(request);
                filterChain.doFilter(request, response);
            }
        }
    }

}